﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Yunchang
{
    public interface ILambdaObject
    {
        void OnGet();
        void OnRelease();
        
    }
    public interface ILambdaObjectPool
    {
        void Release(ILambdaObject element);
    }
    public sealed class LambdaObjectPool
    {
        public static Dictionary<Type, ILambdaObjectPool> cache = new Dictionary<Type, ILambdaObjectPool>();
        public static void Relase(ILambdaObject obj)
        {
            Type type = obj.GetType();
            ILambdaObjectPool pool;
            if (cache.TryGetValue(type, out pool))
                pool.Release(obj);
        }
        public static void Set(Type type, ILambdaObjectPool pool)
        {
            if (!cache.ContainsKey(type))
                cache.Add(type, pool);
        }
    }

    public class LambdaObjectPool<T> : SingletonCSharp<LambdaObjectPool<T>>, ILambdaObjectPool where T : class, ILambdaObject
    {
        private ObjectPool<T> cache = new ObjectPool<T>(OnGet, OnRelease);
        public LambdaObjectPool()
        {
            LambdaObjectPool.Set(typeof(T), this);
        }
        /// <summary>
        /// 获得闭包对象
        /// </summary>
        /// <returns></returns>
        public T Get()
        {
            return cache.Get();
        }

        /// <summary>
        /// 释放闭包对象
        /// </summary>
        /// <param name="element"></param>
        public void Release(T element)
        {
            cache.Release(element);
        }

        public void Release(ILambdaObject element)
        {
            Release((T)element);
        }
        public static void OnGet(T t)
        {
            if (t != null) t.OnGet();
        }
        public static void OnRelease(T t)
        {
            if (t != null) t.OnRelease();
        }
    }
}
